<!DOCTYPE html>
<html>
<head>
    <title>OpenLayers example</title>
    <meta charset="UTF-8"/>
    <link rel="stylesheet" type="text/css" href="css/reset.css"></link>
    <link rel="stylesheet" type="text/css" href="css/map.css"></link>
    <link rel="stylesheet" type="text/css" href="js/layui/css/layui.css"></link>
    <link rel="stylesheet" type="text/css" href="js/openlayers/ol.css"></link>
    <link rel="stylesheet" type="text/css" href="js/openlayers/popup/ol3-popup.css"></link>
    <link rel="stylesheet" type="text/css" href="css/animation.css"></link>
    <script type="text/javascript" src="js/jquery/jquery-1.8.3.min.js"></script>
    <script type="text/javascript" src="js/openlayers/ol.js"></script>
    <script type="text/javascript" src="js/openlayers/ext/ol3-ext.js"></script>
    <script type="text/javascript" src="js/openlayers/popup/ol3-popup.js"></script>

    <style>
        .layui-col-md4 button {
            height: 30px;
            line-height: 30px;
        }
    </style>
</head>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
    <div class="layui-header">
        <div class="layui-logo">OpenLayers example</div>
    </div>
    <div class="layui-body" style="bottom:0px;width: 100%;left:0px;">
        <div class="layui-row" style="width: 100%; height: 100%;">
            <div class="layui-col-md4" style="height: 100%;background: #eee;padding:10px;">
                <button class="layui-btn layui-btn-radius" onclick="zoomOut()">放大</button>
                <button class="layui-btn layui-btn-radius" onclick="zoomIn()">缩小</button>
                <button class="layui-btn layui-btn-radius" onclick="drawLine()">画线</button>
                <button class="layui-btn layui-btn-radius" onclick="drawCircle()">画圆</button>
                <button class="layui-btn layui-btn-radius" onclick="drawPolygon()">画多边形</button>
                <button class="layui-btn layui-btn-radius" onclick="cleanDraw()">清空</button>
                <hr/>
                <hr/>
                经度：<input type="text" name="lon" style="width:100px;"/>
                纬度：<input type="text" name="lat" style="width:100px;"/>
                <button class="layui-btn layui-btn-radius" onclick="getLonlat()">标记一个点</button>
            </div>
            <div class="layui-col-md8" style="height: 100%;">
                <div id="map" style="width: 100%; height: 100%;">
                    <div id="popup" class="ol-popup">
                        <a href="#" id="popup-closer" class="ol-popup-closer"></a>
                        <div id="popup-content"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript" src="js/layui/layui.js"></script>
<script>
    //JavaScript代码区域
    layui.config({
        version: true
    });
    layui.use('element', function () {
        var element = layui.element;

    });
</script>
</body>

<script type="text/javascript">
    window.appMap = {};
    var appMap = window.appMap;
    appMap.id = 'appMap';
    appMap.projection = 'EPSG:3857'; //投影类型
    appMap.mapXyzUrl = 'http://localhost:8080/mapData';

    //用于显示在客户端渲染的矢量数据
    appMap.drawSource = new ol.source.Vector();
    appMap.drawStyle = new ol.style.Style({
        fill: new ol.style.Fill({
            color: 'rgba(255, 255, 255, 0.2)'
        }),
        stroke: new ol.style.Stroke({
            color: '#0398fe',
            width: 2
        }),
        image: new ol.style.Circle({
            radius: 7,
            fill: new ol.style.Fill({
                color: '#0398fe'
            })
        })
    });
    //定义一个画图图层
    appMap.drawVector = new ol.layer.Vector({
        source: appMap.drawSource,
        style: appMap.drawStyle
    });

    //初始化地图
    appMap.map = new ol.Map({
        renderer: 'canvas', //渲染方式
        target: 'map', //容器ID
        logo: null,  //版权log
        loadTilesWhileAnimating: true,
        loadTilesWhileInteracting: true,
        layers: [ //图层
            new ol.layer.Tile({
                source: new ol.source.XYZ({
                    url: appMap.mapXyzUrl + '/roadmap/{z}/{x}/{y}.png'
                })
            }),
            appMap.drawVector
        ],
        view: new ol.View({
            projection: appMap.projection,
            center: ol.proj.fromLonLat([116.3, 39.9]), //默认中心点
            minZoom: 5, //最小缩放级别
            maxZoom: 18, //最大缩放级别
            zoom: 12  //默认缩放级别
        })
    });

    appMap.popup = new ol.Overlay.Popup();
    appMap.map.addOverlay(appMap.popup);

    /**
     * 地图绑定鼠标单击事件
     */
    appMap.map.on('singleclick', function (event) {
        //appMap.popup.hide();
        var feature = appMap.map.forEachFeatureAtPixel(event.pixel,
            function (feature) {
                return feature;
            });
        markSingleClick(feature, event);
    });

    /**
     * 点击到标记时的处理函数
     */
    function markSingleClick(feature, event) {
        if (feature) {
            var geom = feature.getGeometry();
            if (geom instanceof ol.geom.Point) {
                console.log(ol.proj.toLonLat(geom.getCoordinates(), appMap.projection));
                showPopup(feature);//显示泡泡
            }
        }
    }

    /**
     * 地图放大
     */
    function zoomOut() {
        var view = appMap.map.getView();
        var zoom = view.getZoom();
        view.setZoom(zoom + 1)
    }

    /**
     * 地图缩小
     */
    function zoomIn() {
        var view = appMap.map.getView();
        var zoom = view.getZoom();
        view.setZoom(zoom - 1)
    }

    /**
     * 标点
     */
    function mark() {
        addInteractions('Point')
    }

    /**
     * 画线
     */
    function drawLine() {
        addInteractions('LineString')
    }

    /**
     * 画圆
     */
    function drawCircle() {
        addInteractions('Circle')
    }

    /**
     * 画多边形
     */
    function drawPolygon() {
        addInteractions('Polygon')
    }

    /**
     * 注册交互模式
     * @param type
     */
    function addInteractions(type) {
        //清除双击放大效果
        appMap.map.getInteractions().item(1).setActive(false);
        appMap.map.removeInteraction(draw);
        var draw = new ol.interaction.Draw({
            source: appMap.drawSource,
            type: type
        });
        appMap.map.addInteraction(draw);

        draw.on('drawend', function () {
            appMap.map.removeInteraction(draw);
        })
    }

    /**
     * 清空画图
     */
    function cleanDraw() {
        appMap.drawVector.getSource().clear();
    }


    /*  ================================添加矢量数据===================  */

    /**
     * 矢量数据渲染样式
     */
    appMap.markStyle = new ol.style.Style({
        image: new ol.style.Icon({
            anchor: [0.5, 32],
            anchorXUnits: "fraction",
            anchorYUnits: "pixels",
            src: "css/images/map0.png"
        })
    });

    /**
     * 矢量数据源
     */
    appMap.markSource = new ol.source.Vector();

    /**
     * 矢量数据图层
     */
    appMap.markVector = new ol.layer.Vector({
        source: appMap.markSource,
        style: [appMap.markStyle]
    });

    /**
     * 添加图层
     */
    appMap.map.addLayer(appMap.markVector);

    /**
     * 获取坐标并添加标记
     */
    function getLonlat() {
        appMap.map.on("singleclick", function (e) {
            var loaction = e.coordinate;

            var feature = new ol.Feature({
                id: Math.round(Math.random() * 1000000, 0),
                geometry: new ol.geom.Point(loaction),
                move: true
            });

            appMap.markSource.addFeature(feature);


            var point = ol.proj.toLonLat(loaction, appMap.projection);
            $("input[name='lon']").val(point[0]);
            $("input[name='lat']").val(point[1]);

            //解除事件监听
            appMap.map.removeEventListener("singleclick");
        })

    }

    /**
     *  显示泡泡
     */
    function showPopup(feature) {
        var html = '<div style="width: 200px; height: 100px;">' +
            '<h4>这是一个泡泡</h4>' +
            '<button onclick="removeMark(' + feature.get("id") + ')">删除这个标记</button>' +
            '</div>';
        appMap.popup.show(feature.getGeometry().getLastCoordinate(), html);
    }

    /**
     * 根据id移除标记并关闭泡泡
     * @param featureId
     */
    function removeMark(featureId) {
        var features = appMap.markSource.getFeatures();
        for (var i = 0; i < features.length; i++) {
            if (features[i].get("id") == featureId) {
                appMap.markVector.getSource().removeFeature(features[i]);
                appMap.popup.hide();
            }
        }
    }
</script>
</html>